<?php
namespace app\controller\admin;

use app\helper\tools\Security;
use app\models\User;
use app\validate\admin\AuthValidate;
use Gregwar\Captcha\CaptchaBuilder;
use think\facade\Session;
use think\Request;

class Auth extends Application
{
    public function initialize()
    {
        if ($this->request->action() == 'index' && session('admin_login_id')) {
            $this->redirect('admin/dashboard/index');
        }
    }

    public function index()
    {
        //初始化登陆次数
        if (Session::has('admin_login_count')) {
            $meta['count'] = session('admin_login_count');
        } else {
            $meta['count'] = 0;
        }

        $siteTitle = '后台登陆';

        return view('admin/login', compact(['meta', 'siteTitle']));
    }

    public function captcha()
    {
        $builder = CaptchaBuilder::create();
        $builder->build();
        session('captcha_word', $builder->getPhrase());
        return response()->data($builder->output())->contentType('image/jpeg');
    }

    /**
     * 刷新验证码图
     */
    public function refresh()
    {
        return $this->formatResult(0, 'success', ['url' => url('admin/auth/captcha')]);
    }

    public function login(Request $request)
    {
        $count = session('admin_login_count');
        $count++;
        session('admin_login_count', $count);

        $result = $this->validate(
            $request->only(['email', 'password', 'captcha', '_token']),
            AuthValidate::class
        );

        if (true !== $result) {
            return $this->formatResult(-1, $result, [
                'url' => url('admin/auth/captcha'),
                'count' => $count,
                'token' => $request->token('_token')
            ]);
        }

        $email = $request->param('email');
        $pass = $request->param('password');
        $captcha = $request->param('captcha');

        if ($request->isAjax() && $request->method() == 'POST' && $email && $pass) {
            if ($count > 3) {
                $captchaOriginal = Session::pull('captcha_word');
                if ($captcha != $captchaOriginal) {
                    return $this->formatResult(1, '验证码错误', [
                        'url' => url('admin/auth/captcha'),
                        'count' => $count,
                        'token' => $request->token('_token')
                    ]);
                }
            }
            list($ret, $user) = $this->checkLogin($email, $pass);
            if ($ret) {
                session('admin_login_count', 0);
                session('admin_login_id', $user[$user->getPk()]); //返回uid
                session('admin_login_name', $user['name']); //返回uid
                return $this->formatResult(0, '登陆成功', ['url' => url('admin/dashboard/index')]);
            } else {
                return $this->formatResult(1, $user, [
                    'url' => url('admin/auth/captcha'),
                    'count' => $count,
                    'token' => $request->token('_token')
                ]);
            }
        }
        return $this->formatResult(2, '登陆失败', [
            'url' => url('admin/auth/captcha'),
            'count' => $count,
            'token' => $request->token('_token')
        ]);
    }

    public function logout()
    {
        session('admin_login_id', 0);
        session('admin_login_name', '');
        $this->redirect('admin/login');
    }

    protected function checkLogin($email, $pass)
    {
        $user = User::where(['email' => $email])->where('status', 1)->find();
        if ($user) {
            $userPass = Security::decrypt($user['password'], config('security.app_key'));
            if ($pass === $userPass) {
                return [true, $user];
            } else {
                return [false, '帐户或密码错误'];
            }
        }
        return [false, '无效帐户'];
    }
}
